#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi
import datetime
import wsgiref.handlers
import webapp2

from google.appengine.ext import db
from google.appengine.api import users
#from google.appengine.ext import webapp2

class Device(db.Model):
  name = db.StringProperty()
  ip = db.StringProperty()
  date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp2.RequestHandler):
  def get(self):

    self.response.out.write('<html>')
    self.response.out.write('<title>JetWave Dynamic IP Remote Access</title>')
    self.response.out.write('<link rel="stylesheet" href="/stylesheets/nb.css" type="text/css">')
    #self.response.out.write('<script type="text/javascript" src="./javascripts/common.js"> </script>')
    self.response.out.write('<script language="JavaScript">')
    self.response.out.write('document.getElementById("manualInput").style.display="none"')
    self.response.out.write('</script>')


    self.response.out.write('<body>')
    self.response.out.write('<img rel="images" src="/images/topbg.jpg">')


    #devices = db.GqlQuery("SELECT * "
    #                        "FROM Device "
    #                        "ORDER BY date DESC LIMIT 10")

    #q = db.Query(Device).filter('name', 'korenixffff')
    #device = q.get()

    q = db.Query(Device)
    devices = q.fetch(10)


    self.response.out.write('<table width="60%" cellspacing="1" class="tablesorter">')
    self.response.out.write('<tr><th>Device Name</th><th>IP Address</th><th>Last Update Time</th></tr>')
    for device in devices:
    #if device:
      self.response.out.write(
              '<tr><td>%s</td><td><a href="https://%s">%s</a></td><td>%s</td></tr>' %
          (device.name, device.ip, device.ip, ((device.date + datetime.timedelta(hours=+8)).strftime("%Y-%m-%d %H:%M:%S"))))
    self.response.out.write('</table><br><br>')

    self.response.out.write('<span class="style1"><font color="red">Note: Some of the mobile operators block port 80. You MUST enable <b>force https</b> connection on JetWave.</color></span>')
  

    self.response.out.write('<div id="form_sub_container1" style="display: none;">')
    self.response.out.write(""" <form action="/mark" method="get" id="manualInput">
      <table>
      <tr><td><div>Device Name     : </td><td><input type="text" name="name"></div></td></tr>
      <tr><td><div>Device IP       : </td><td><input type="text" name="ip"></div></td></tr>
      </table>
      <div><input type="submit" value="Submit"></div>
      </form></body></html>""")
    self.response.out.write('</div>')


class UpdateDevice(webapp2.RequestHandler):
  def get(self):

    # Create instance of FieldStorage 
    form = cgi.FieldStorage() 
    
    q = db.Query(Device).filter('name', form.getvalue('name'))
    update = q.get()

    if update:
        update.ip = form.getvalue('ip')
        update.date = datetime.datetime.now()
        update.put()
    else:
        device = Device()
        # Get data from fields
        device.name = form.getvalue('name')
        device.ip = form.getvalue('ip')
        device.put()

    self.redirect('/')


application = webapp2.WSGIApplication([
  ('/', MainPage),
  ('/mark', UpdateDevice)
], debug=True)


def main():
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
